<template>
  <div>
    <DynamicTable
      ref="dynamicTableRef"
      row-key="id"
      :header-title="$t('routes.system.system.config.wxApplet')"
      :data-request="loadData"
      :columns="columns"
      bordered
      size="small"
      :showIndex="false"
      :fetch-config="{ listField: 'data', totalField: 'count' }"
    >
      <template #toolbar>
        <a-button v-if="canAdd" type="primary" @click="edit">
          {{ $t('common.add') }}
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>
<script lang="tsx" setup>
  import { ref } from 'vue'
  import { message } from 'ant-design-vue'
  import { DynamicTable } from '@/components/core/dynamic-table'
  import { useFormModal } from '@/hooks/useModal/useFormModal'
  import type { FormSchema } from '@/components/core/schema-form/src/types/form'
  import type { TableColumn } from '@/components/core/dynamic-table'
  import { useI18n } from '@/hooks/useI18n'
  import { ApiDescription, HttpMethod } from '@/utils/apiDescription'
  import canAccessView from '@/utils/accessCheck'
  import { wxApplet, addwxApplet, updatewxApplet, delwxApplet } from '@/api/middleSystem'

  defineOptions({
    name: 'WxApplet',
  })

  const canAdd = ref(canAccessView(new ApiDescription(addwxApplet.baseUrl, addwxApplet.method)))
  const canUpdate = ref(
    canAccessView(new ApiDescription(updatewxApplet.baseUrl, updatewxApplet.method)),
  )
  const canDelete = ref(canAccessView(new ApiDescription(delwxApplet.baseUrl, delwxApplet.method)))

  const { t } = useI18n()
  const dynamicTableRef = ref<InstanceType<typeof DynamicTable>>()

  /**
   * 表格列
   */
  const columns: TableColumn<any>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: 'appid',
      dataIndex: 'appid',
      hideInSearch: true,
    },
    {
      title: 'secret',
      dataIndex: 'secret',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'ACTION',
      hideInSearch: true,
      actions: ({ record }) => [
        {
          label: t('common.edit'),
          hide: !canUpdate.value,
          onClick: () => edit(record),
        },
        {
          label: t('common.delete'),
          danger: true,
          hide: !canDelete.value,
          popConfirm: {
            title: t('column.confirmDel'),
            onConfirm: () => del(record),
          },
        },
      ],
    },
  ]

  /**
   * 加载数据
   */
  const loadData = async params => {
    const { name, pageIndex, pageSize } = params
    const data = await wxApplet.request({ page: pageIndex, pageSize: pageSize, name: name })
    return data
  }

  const [showModal] = useFormModal()
  const formSchemas: FormSchema[] = [
    {
      field: 'name',
      component: 'Input',
      label: '名称',
      rules: [{ required: true }],
    },
    {
      field: 'appid',
      component: 'Input',
      label: 'appid',
      rules: [{ required: true }],
    },
    {
      field: 'secret',
      component: 'Input',
      label: 'secret',
      rules: [{ required: true }],
    },
  ]

  /**
   * 打开新增/编辑弹窗
   */
  const edit = async record => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? t('common.edit') : t('common.add')}`,
        width: '40%',
        onFinish: async values => {
          const { name, appid, secret } = values
          if (record.id)
            await updatewxApplet.request(record.id, { name: name, appid: appid, secret: secret })
          else await addwxApplet.request({ name: name, appid: appid, secret: secret })
          message.success('操作成功')
          dynamicTableRef.value?.reload()
        },
      },
      formProps: {
        labelWidth: 100,
        layout: 'horizontal',
        schemas: record.appId
          ? formSchemas.filter(
              item => item.field !== 'endpoints.protocol' && item.field !== 'appId',
            )
          : formSchemas,
      },
    })

    if (record.id) {
      formRef?.setFieldsValue({
        name: record.name,
        appid: record.appid,
        secret: record.secret,
      })
    }
  }

  /**
   * 删除
   */
  const del = async record => {
    await delwxApplet.request(record.id)
    message.success('操作成功')
    dynamicTableRef.value?.reload()
  }
</script>
